import {
  ChangeDetectorRef,
  Component,
  OnInit,
  Renderer2,
  AfterViewChecked,
  ChangeDetectionStrategy,
} from '@angular/core';
import { GridConfigService } from '@core/config/grid-config.service';
import { GridOptions } from '@ag-grid-community/core';
import { ApiService } from '@core/services/http/api.service';
import { FormGroup } from '@angular/forms';
import { ActivatedRoute } from '@angular/router';
import { ExportExcelService } from '@core/services/excel/export-excel.service';
import { saveAs } from 'file-saver';
import {
  agCurrency, agNumber,
  dateFormat,
  deepClone, exists, fillField, getO,
  replaceAll,
  type,
} from '../../utils/utils';
import { ApesMessageService } from '@shared/apes/message';
import { ApesRenderSelectComponent } from '@shared/ag-grid-ext/cell-renders/render-select.component';
import { ReuseTabService } from '@shared/apes/reuse-tab';
import { MenuService } from '@core';
import { toBoolean } from '@shared/apes/core/util/convert';
import { ApesContextMenuService } from '@shared/ag-grid-ext/context-menu/';
import { RenderOperatingButtonComponent } from '@shared/ag-grid-ext/cell-renders/render-operating-button.component';
import { ExpressionService } from '@core/services/expression/ExpressionService';
import { FormService } from '@core/services/form.service';
import { SubjectService } from '@core/services/events/subject.service';
import { FormlyFormOptions } from '@ngx-formly/core';
import { UserAuthService } from '@core/services/user-auth.service';
import { ApesLoadingOverlayComponent } from '@shared/ag-grid-ext/loading-overlay/apes-loading-overlay.component';
import { Events } from '@core/services/events/Events';


import { AllModules, Module } from '@ag-grid-enterprise/all-modules';
import { XlsxService } from '@shared/apes/xlsx';
import { CustomHeaderComponent } from '@shared/ag-grid-ext/header-component/custom-header.component';
import { RenderUploadComponent } from '@shared/ag-grid-ext/cell-renders/render-upload.component';
import { RenderMultipleLinesComponent } from '@shared/ag-grid-ext/cell-renders/render-multipleLines.component';
import { BatchPrintService } from './batch-print/batch-print.service';
import { format } from 'date-fns';
import { RenderDetailComponent } from '@shared/ag-grid-ext/cell-renders/render-detail.component';
import { RenderCustomDetailComponent } from '@shared/ag-grid-ext/cell-renders/render-custom-detail.component';
import { RenderTooltipComponent } from '@shared/ag-grid-ext/cell-renders/render-tooltip.component';
import { ButtonService } from '@core/services/button.service';
import { RenderXmlDetailComponent } from '@shared/ag-grid-ext/cell-renders/render-xml-detail.component';
import { ApesRenderDefaultComponent } from '@shared/ag-grid-ext/cell-renders/render-default.component';

@Component({
  selector: 'apes-query',
  templateUrl: './apes-query.component.html',
  // styleUrls: ['./apes-query.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class ApesQueryComponent implements OnInit, AfterViewChecked {
  frameworkComponent: any;
  private gridApi;
  private gridColumnApi;
  //statusBar;
  getContextMenuItems;
  rowClassRules = {};
  private contextMenu = [];
  modules: Module[] = AllModules;
  /** 按钮列表 **/
  buttonBar = [];
  title = '';
  ctx: any = {};
  tableValid = {};
  showMoreBtn = false;
  showData = true;
  showRow = 6;
  downloadPage = 0;
  isDownloading = false;
  percent = 0;

  /** 分页器 **/
  loadingTotal = 0;
  pagination = {
    total: 0,
    currentPage: 0,
    lastRow: -1,
    pageSize: 50,
    pages: 0,
  };

  /**关联跳转**/
  relevancyMetadata;

  /** Grid 相关 **/
  rowData: any[];
  resultData: any;
  gridOptions: GridOptions;
  rowModelType: any;
  pinnedBottomRowData: any[];

  /** List 相关 **/
  listData: any[] = [];
  listOptions: any = {};

  /** Iframe 相关 **/
  iframeUrl: any = '';
  iframeShowUrl: any = ''; // http://www.biying.com
  iframeShowType: any = 'preview';
  iframeLoading: any = true;

  /** form 定义相关 **/
  form: FormGroup;
  model: any = {};
  options: FormlyFormOptions = {};
  /**用户信息**/
  user: any;

  /** 从接口取数 **/
  conditionField: any[] = [];
  queryConditions: boolean = false; // 必填查询条件
  showConditionField: any[] = [];
  api = '';
  customAction = false; // 是否插入前置处理
  customQuery = false; // 是否使用第三方查询
  customQueryInit = false; // 初始化动态查询默认值
  columnDefs: any[];
  columnDefsMeta: any[];
  headerGroup = [];
  formId = '';    // 表单XML编码
  sideBar = '';
  enableSorting = false;
  enableFilter = false;
  currRowIndex = 0;

  btnQuery: boolean = false;

  /** 合计相关 **/
  noSum: boolean = false; //设为true 为后端合计只在第一页合计
  loadingOverlayComponent: any;
  /**订阅主题**/
  subjects = {};
  // showType = false;
  tables = [];

  btnRemarks: any = '';

  searchShowType: any = 'grid';

  suppressRowClickSelection: boolean = true;
  rowSelection: any = 'single';
  printTemplate: any = '';

  isDetail: boolean = false;
  isRowMaster: any;
  detailCellRenderer: any;
  detailCellRendererParams: any;
  detailList: any;
  detailRowHeight: any = '100';
  detailRowOptions: any;

  hideBtnBar: boolean = false;
  buttonList: any[] = [];

  constructor(gridConfigService: GridConfigService,
              private msg: ApesMessageService,
              private apiService: ApiService,
              private route: ActivatedRoute,
              private exportExcelService: ExportExcelService,
              protected reuseTabService: ReuseTabService,
              private renderer: Renderer2,
              protected menuService: MenuService,
              private contextService: ApesContextMenuService,
              protected expressionService: ExpressionService,
              protected subject: SubjectService,
              protected userService: UserAuthService,
              protected formService: FormService,
              protected events: Events,
              private xlsx: XlsxService,
              private batchPrintService: BatchPrintService,
              private buttonService: ButtonService,
              private readonly changeDetectorRef: ChangeDetectorRef) {

    this.formId = this.route.snapshot.paramMap.get('formId');

    // 初始化 grid
    this.gridOptions = <GridOptions>{
      suppressExcelExport: true,
      suppressCsvExport: true,
      showToolPanel: false,
    };
    this.frameworkComponent = {
      renderSelect: ApesRenderSelectComponent,
      dialogButton: RenderOperatingButtonComponent,
      loadingOverlay: ApesLoadingOverlayComponent,
      customHeader: CustomHeaderComponent,
      upload: RenderUploadComponent,
      renderMultipleLines: RenderMultipleLinesComponent,
      detail: RenderDetailComponent,
      customDetail: RenderCustomDetailComponent,
      renderTooltip: RenderTooltipComponent,
      xmlDetail: RenderXmlDetailComponent,
      renderDefault: ApesRenderDefaultComponent,
    };
    this.loadingOverlayComponent = 'loadingOverlay';
    this.gridOptions.localeText = gridConfigService.getLocaleText();
    // this.statusBar = {
    //   statusPanels: [
    //     {
    //       statusPanel: "agTotalRowCountComponent",
    //       align: "left"
    //     },
    //     { statusPanel: "agFilteredRowCountComponent" },
    //     { statusPanel: "agSelectedRowCountComponent" },
    //     { statusPanel: "agAggregationComponent" }
    //   ]
    // };
  }

  ngAfterViewChecked(): void {
    this.changeDetectorRef.markForCheck();
    this.changeDetectorRef.detectChanges();
  }

  /**
   * 功能：初始化上下文环境变量
   */
  private initContext() {
    this.ctx.model = this.model;
    this.ctx.states = 'submit';
    this.ctx.form = this.form;
    this.ctx.user = this.user;
    this.ctx.subjects = this.subjects;
    this.options.formState = this.ctx;
    this.ctx['this'] = this;
    this.ctx.platform = this.userService.getUserInfoObj() ? this.userService.getUserInfoObj().platform : ''; // 判断平台
    this.model['platform'] = this.ctx.platform;
  }

  ngOnInit() {

    this.setContentHeight();

    this.form = new FormGroup({});
    this.rowModelType = ''; //infinite clientSide serverSide
    // 获取表单的数据
    /**拉模型：组件创建时初始化**/
    this.userService.getUser().subscribe(user => {
      this.user = user;
      this.ctx.user = this.user;
    });

    /**推模型：数据变更时主动触发**/
    this.userService.userSubject.subscribe(user => {
      this.user = user;
      this.ctx.user = this.user;
    });
    this.initContext();
    this.getRenderData();

    this.events.subscribe(this.getUrl(), data => {
      this.executeTask(data);
    });
  }

  ngAfterViewInit() {


    this.subject.subscribe(this.ctx, 'changeShowType', data => {
      let index = parseInt(data.id);
      console.log(this.model);
      this.resetColumnDefs(this.tables[index].columnDefs);
      this.resetModel();
      if (this.tables[index].hasOwnProperty('buttonList')) {
        let btnList = this.tables[index].buttonList;
        this.initBtnList(btnList);
      } else {
        this.buttonList = [];
      }
      this.api = data.api;
      this.resetGridData();
      this.customQuery = data.customQuery ? data.customQuery : this.customQueryInit;
      if (this.btnQuery || data.btnQuery) {
        setTimeout(() => {
          this.action_query();
          this.setContentHeight();
        }, 500);
      }
    });

    this.subject.subscribe(this.ctx, 'changeLabelList', data => {
      if (data && data.hasOwnProperty('showType')) {
        let index = parseInt(data.id);
        this.resetColumnDefs(this.tables[index].columnDefs);
        if (this.tables[index].hasOwnProperty('buttonList')) {
          let btnList = this.tables[index].buttonList;
          this.initBtnList(btnList);
        } else {
          this.buttonList = [];
        }
        this.api = data.api;
        this.action_query();
        this.setContentHeight();
      } else {
        this.action_query();
      }
    });

    this.subject.subscribe(this.ctx, 'resetData', data => {

      // if (this.rowModelType == 'serverSide') {
      //   let dataSource = {
      //     rowCount: null,
      //     getRows: (params: any) => {
      //       params.successCallback([], 0);
      //     },
      //   };
      //   this.gridApi.setServerSideDatasource(dataSource);
      // } else {
      //   this.rowData = [];
      // }

      this.resetGridData();

    });

    this.subject.subscribe(this.ctx, 'clickBtn', data => {
      this.actionType(data);
    });

    this.subject.subscribe(this.ctx, 'updateData', data => {
      this.gridApi.applyTransaction({ update: data });
    });

    this.subject.subscribe(this.ctx, 'removeData', data => {
      this.gridApi.updateRowData({ remove: data });
      setTimeout(() => {
        let newRow = this.getNowRows();
        this.gridApi.applyTransaction({ update: newRow });
      }, 500);
    });

    this.subject.subscribe(this.ctx, this.subject.event_button, data => {
      this.buttonService.clickButton(data);
    });
  }

  private setContentHeight() {
    // 获取 container 元素
    let containerHeight = document.querySelector('.content').clientHeight;
    setTimeout(() => {
      let apesGrid = document.querySelector('.query-grid');
      let apesPaging = document.querySelector('.apes-grid-footer').clientHeight;
      let apesSearch = document.querySelector('.query-search').clientHeight;

      if (this.hideBtnBar || (this.relevancyMetadata && this.relevancyMetadata['links'])) {
        let apesContainer = document.querySelector('.apes-container');
        let relevancyHeight = this.relevancyMetadata['links'] ? 50 + 38 : 0;
        let hideBtnBarHeight = this.hideBtnBar ? 87 + 84 : 0;
        let contentHeight = containerHeight - hideBtnBarHeight - relevancyHeight + 'px';
        this.renderer.setStyle(apesContainer, 'height', contentHeight);
      }

      let apesItemHeight = 16;
      let apesScrollPanel = 16; // 横向滚轮
      let hideBtnBar;
      let relevancyHeight = (this.relevancyMetadata && this.relevancyMetadata['links']) ? 38 : 0;
      let platform = this.userService.getUserInfoLocalObj() ? this.userService.getUserInfoLocalObj().platform : '';
      if (!platform) {
        this.renderer.setStyle(apesGrid, 'height', containerHeight - apesItemHeight - apesSearch - 32 - 40 - 46 + 'px');
      } else {

        let apesGridHeight;
        if (this.searchShowType == 'grid') {
          hideBtnBar = this.hideBtnBar ? -27 : 28;
          // - apesPaging
          apesGridHeight = containerHeight - apesItemHeight - apesScrollPanel - apesSearch - 32 - 40 - hideBtnBar - relevancyHeight - 46 + 'px';
        } else if (this.searchShowType == 'list' || this.searchShowType == 'iframe') {
          hideBtnBar = this.hideBtnBar ? -54 : 0;
          apesGridHeight = containerHeight - apesItemHeight - apesSearch - 32 - 20 - hideBtnBar - relevancyHeight - 59 + 'px';
        }
        this.renderer.setStyle(apesGrid, 'height', apesGridHeight);
      }
    }, 1000);
  }

  private getUrl(): string {
    let url = 'report/' + this.route.snapshot.paramMap.get('formId');
    return url;
  }

  private executeTask(taskMetadata) {

    this.form.reset(); // 重置界面查询条件

    setTimeout(() => {
      delete this.formService.formData['key'];

      // 写入下拉控件下拉值
      let keys = Object.keys(taskMetadata);
      this.showConditionField.forEach(field => {

        if (keys.indexOf(field.key) !== -1) {
          // 判断当前元素是否为下拉框
          if (field.templateOptions.config.type === 'select') {
            // 判断当前是否含有 key + _name 字段
            if (taskMetadata[field.key] && taskMetadata[field.key + '_name']) {
              if (taskMetadata[field.key] instanceof Array) {
                let items = [];
                taskMetadata[field.key].forEach((item, index) => {
                  items.push({
                    id: item,
                    name: taskMetadata[field.key + '_name'][index],
                  });
                });
                field.templateOptions.componentRef.items = items;
                // this.form.get(field.key).patchValue(items);
                // field.formControl.patchValue(items)
              } else {
                let value = {
                  id: taskMetadata[field.key],
                  name: taskMetadata[field.key + '_name'],
                };
                field.templateOptions.componentRef.items = [value];
                // this.form.get(field.key).patchValue(value);
                // field.formControl.patchValue(value)
              }
            }
          }
          // } else if(taskMetadata[field.key] != null && taskMetadata[field.key] != undefined){
          //   field.formControl.patchValue(taskMetadata[field.key]);
          // }

        }
      });

      this.model = { ...taskMetadata };
      // 设置查询条件并查询
      if (taskMetadata.hasOwnProperty('changeShowType')) {
        let data = taskMetadata.changeShowType;
        data['btnQuery'] = true;
        this.subject.publish(this.ctx, 'changeShowType', data);
      } else {
        this.action_query();
      }//用于跳转切换查询api
    }, 500);
  }

  /**
   * 获取到可以操作的按钮
   * @param buttons
   */
  private getAuthButton(buttons: any): any[] {
    let operations = this.getOperations();

    let authButtonList = operations.filter((button) => {
      if (button.operationId !== 'action_view') {
        button['label'] = button.name;
        button['style'] = 'default';
        button['loading'] = false;
        return button;
      }
    });

    return buttons.concat(authButtonList);
  }

  /**
   * 功能：获取当前页面可操作按钮信息
   * @returns {any[]}
   */
  private getOperations(): any[] {
    let menu = this.getMenu();
    if (menu && menu.operations) {
      return menu.operations;
    }
    return [];
  }

  /**
   * 功能：获取当前页面菜单信息
   * @returns {any}
   */
  private getMenu() {
    let curURL = this.reuseTabService.getUrl(this.route.snapshot);
    const menus = this.menuService ? this.menuService.getPathByUrl(curURL) : [];
    if (!menus || menus.length === 0) return null;
    return menus.pop();
  }

  /**
   * 功能： 获取展示的按钮
   * @returns {any[]}
   */
  getButtonMetaData(showMore: boolean): any[] {
    let buttonMetaData = [
      { style: 'primary', label: '查询', operationId: 'action_query', api: '', loading: false },
      { style: 'default', label: '列设置', operationId: 'action_columnConfig', api: '', loading: false },
      { style: 'default', label: '重置查询条件', operationId: 'action_reset', api: '', loading: false },
      /* { style: 'default', label: '导出', operationId: 'action_export', api: ''},
       { style: 'default', label: '下载', operationId: 'action_download', api: ''},*/
    ];
    // if (showMore) {
    //   let more = { style: 'default', label: '展开查询条件', operationId: 'action_showMore', api: '', loading: false };
    //   buttonMetaData.push(more);
    // }
    return buttonMetaData;
  }

  /**
   * 功能：获取表单以及Grid列的数据
   */
  getRenderData(formId ?: any) {
    if (formId == undefined) {

    }
    this.apiService.post('form.search.get', { 'body': JSON.stringify({ 'id': this.formId }) }).subscribe(
      (body) => {
        console.log(body);
        this.conditionField = body.conditionField;
        this.queryConditions = body.queryConditions ? body.queryConditions : false;
        this.formService.extFormMetadata(this.conditionField, this.ctx, this.subject, this.tableValid);

        this.api = body.api;

        this.customAction = body.customAction ? body.customAction === 'true' ? true : false : false;
        this.customQuery = body.customQuery ? body.customQuery === 'true' ? true : false : false;
        this.customQueryInit = body.customQuery ? body.customQuery === 'true' ? true : false : false;
        if (body.hasOwnProperty('searchShowType')) {
          this.searchShowType = body.searchShowType;
          if (body.searchShowType == 'list') {
            this.listOptions['api'] = this.api;
            this.listOptions['customAction'] = this.customAction;
            this.listOptions['customQuery'] = this.customQuery;
          } else if (body.searchShowType == 'iframe') {
            this.iframeUrl = body.url;
            this.iframeShowType = body.showType ? body.showType : 'preview';
          }
        }

        if (body.hasOwnProperty('relevancy')) {
          this.relevancyMetadata = body.relevancy;
        }

        this.btnRemarks = body.btnRemarks ? body.btnRemarks : '';
        if (body.hasOwnProperty('headerGroup')) {
          this.headerGroup = body.headerGroup;
        }

        if (body.hasOwnProperty('btnQuery')) {
          this.btnQuery = toBoolean(body.btnQuery);
        }

        if (body.hasOwnProperty('detailType')) {
          this.isDetail = true;
          this.detailCellRenderer = body.detailType;
          this.detailRowHeight = body['detailRowHeight'] ? body['detailRowHeight'] : '100';
          this.detailRowOptions = body['detailRowOptions'] ? getO(body['detailRowOptions']) : null;
          if (this.detailCellRenderer == 'detail') {
            this.detailList = body['detailList'];
            this.isRowMaster = (dataItem) => {
              if (this.detailCellRenderer == 'detail') {
                return dataItem ? dataItem[this.detailList].length > 0 : false;
              } else {
                return true;
              }
            };
          }
        }

        if (body.hasOwnProperty('tables')) {
          // this.showType = true;
          body['tables'].forEach(item => this.tables.push(deepClone(item)));
          this.resetColumnDefs(this.tables[0].columnDefs);
          if (this.tables[0].hasOwnProperty('buttonList')) {
            let btnList = this.tables[0].buttonList;
            this.initBtnList(btnList);
          } else {
            this.buttonList = [];
          }
        } else {
          // this.showType = false;
          this.resetColumnDefs(body.columnDefs);
          if (body.hasOwnProperty('buttonList')) {
            let btnList = body.buttonList;
            this.initBtnList(btnList);
          } else {
            this.buttonList = [];
          }
        }

        if (body.hasOwnProperty('printTemplate')) {
          this.rowSelection = 'multiple';
          this.suppressRowClickSelection = true;
          this.printTemplate = body.printTemplate;
        }

        if (body.hasOwnProperty('showRow')) {
          this.showRow = body.showRow;
        }

        // 判断是否增加排序条件
        if (!body.sortable) {
          this.conditionField.push(this.orderFilePush()); // 增加排序字段
          this.conditionField.push(this.orderTyepPush()); // 增加升/降序
        }

        this.ctx.$showConditionField = this.conditionField;

        this.title = body.title;
        if (body.hasOwnProperty('rowModelType')) {
          this.enableFilter = true;
          this.enableSorting = true;
          this.rowModelType = 'clientSide';
        } else {
          this.enableFilter = false;
          this.enableSorting = false;
          this.rowModelType = 'serverSide';
          this.gridOptions.cacheBlockSize = 50;
          this.gridOptions.infiniteInitialRowCount = 1;
          this.gridOptions.pagination = false;
          //this.gridOptions.maxBlocksInCache =100;
          this.gridOptions.paginationPageSize = this.pagination.pageSize;
        }

        // 设置是否合计
        this.noSum = body.noSum ? toBoolean(body.noSum) : false;
        this.rowClassRules = body.rowClassRules ? body.rowClassRules : { 'selected': 'data.A ==true' };
        if (body.contextMenu) {
          body.contextMenu.forEach(item => {
            this.contextMenu.push(item);
          });
        }
        // 获取权限
        let btnList;
        this.menuService.change.subscribe(
          data => {
            if (data && data.length > 0) {
              if (this.conditionField.length > this.showRow) {
                btnList = this.getAuthButton(this.getButtonMetaData(true));
                this.showMore(false);
                this.showMoreBtn = true;
              } else {
                btnList = this.getAuthButton(this.getButtonMetaData(false));
                this.showMore(true);
                this.showMoreBtn = false;
              }
              this.buttonBar = btnList;
              this.ctx['customBtn'] = this.buttonBar;
            }
          });

        if (this.formService.formData.hasOwnProperty('key')) {
          this.executeTask(this.formService.formData['key']);
        }

        if (body.hasOwnProperty('hideBtnBar')) {
          this.hideBtnBar = true;
          this.setContentHeight();
        }
      });

    this.getContextMenuItems = (params) => {
      let headerName = params.column.colDef.headerName;
      let key = params.column.colId;
      let result = [
        'copy',
        'separator',
        {
          name: params.value ? headerName + ' : ' + params.value : '无数据', action: () => {
          },
        },
        // {
        //   name: 'Alert ' + params.value,
        //   action: function() {
        //     console.log(params);
        //     window.alert('Alerting about 1' + params.value);
        //   },
        // },
      ];

      this.contextMenu.forEach(item => {
        let context = this.contextService;
        let data = params.node.data;
        let config = item.config;
        result.push({
          name: item.name,
          action: () => {
            if (item.action == 'dialog') {
              // context.openContextDailog(data, null, config);
              context.openContextDynamicDailog(data, item.api, key, null, config);
            } else if (item.action == 'drawer') {
              context.openContextDrawer(data, null, config);
            } else if (item.action == 'link') {
              context.openContextLink(data, item.api, config);
            }
          },
        });
      });
      return result;
    };
  }

  initBtnList(btnList) {
    this.buttonList = btnList;
  }

  private getNowRows(): any[] {
    let rows = [];
    this.gridApi.selectAll();
    this.gridApi.getSelectedNodes().forEach((node) => {
      rows.push(node.data);
    });
    return rows;
  }


  /**
   * 功能：按钮事件路由
   * @param data 当前按钮元数据
   */
  onEvent(data: any) {
    if (data instanceof MouseEvent) return;
    if (data) {
      let type = data.operationId;
      this.actionType(type);
    }
  }

  actionType(type) {
    if (type === 'action_query') {
      if (this.searchShowType == 'grid') {
        this.action_query();
      } else if (this.searchShowType == 'list') {
        this.queryListData();
      } else if (this.searchShowType == 'iframe') {
        this.queryIframeData();
      }
    } else if (type === 'action_reset') {
      this.action_reset();
    } else if (type === 'action_showMore') {
      this.action_showMore();
    } else if (type === 'action_columnConfig') {
      this.action_columnConfig();
    } else if (type === 'action_download') {
      this.action_download();
    } else if (type === 'action_print') {
      this.action_print();
    } else if (type === 'action_export') {
      this.action_export();
    }
  }


  /**
   * 功能：查询事件
   */
  action_query(): void {
    this.pagination.currentPage = 0;   // 每次点击查询按钮时，重置 currentPage
    this.pagination.lastRow = -1;
    this.gridApi.forEachNode((node) => {
      node.setSelected(false);
    });  // 用于解决批量打印问题
    this.queryData();
  }

  /**
   * 功能：重置查询条件
   */
  action_reset(): void {
    this.form.reset();

    this.resetDefaultValue(this.conditionField);
  }

  /**
   *  重置条件还原默认值
   */

  resetDefaultValue(conditionField) {
    for (const tempConditionField of conditionField) {
      let key = tempConditionField.key;
      if (this.model[key]) {
        this.model[key] = null;
        if (this.model.hasOwnProperty(key + '_name')) {
          this.model[key + '_name'] = null;
        }
      }
      if (!tempConditionField.hasOwnProperty('defaultValue')) continue;
      let fieldId = tempConditionField.key;

      if (tempConditionField['defaultValue'] !== undefined && tempConditionField['defaultValue'] !== null) {
        let defaultValue = tempConditionField['defaultValue'];
        let type = tempConditionField.templateOptions.config.type;
        const config = tempConditionField.templateOptions.config;

        // this.value = this.to['defaultValue'];
        if (config.type === 'select' && defaultValue.indexOf('ctx.') > -1) {
          defaultValue = this.expressionService.evaluate(defaultValue, { context: this.ctx }, false);
          if (defaultValue) {
            tempConditionField.formControl.patchValue(defaultValue);
            return;
          } else {
            tempConditionField.formControl.patchValue(null);
            return;
          }
        } else if (config.type == 'dateRange') {
          tempConditionField.formControl.patchValue([new Date(), new Date()]);
          return;
        }
        if (type === 'boolean') {
          this.model[fieldId] = toBoolean(defaultValue);
          tempConditionField.formControl.patchValue(this.model[fieldId]);
          return;
        }
        if (config.type === 'radio') {
          if (defaultValue == 'all') {
            tempConditionField.formControl.patchValue(null);
            return;
          }
        }

        if (this.model.hasOwnProperty(fieldId) && defaultValue != this.model[fieldId] && defaultValue != 'true') {
          this.model[fieldId] = defaultValue;
          tempConditionField.formControl.patchValue(defaultValue);
        }
      }
    }
  }

  /**
   * 功能：展开查询条件
   */
  action_showMore() {
    if (this.showData) {
      this.showMore(true);
      this.showData = false;
    } else {
      this.showMore(false);
      this.showData = true;
    }
  }

  showMore(show: boolean) {
    // let condition  = this.conditionField.slice(0);
    // for (let i = 0; i > condition.length; i++) {
    //   if (condition[i].key == this.showConditionField[i].key) {
    //     condition[i] = {...this.showConditionField[i]};
    //   }
    // }
    // this.conditionField = condition;
    if (show) {
      this.showConditionField = this.conditionField;
    } else {
      let data = [];
      for (let i = 0; i < this.showRow; i++) {
        data.push(this.conditionField[i]);
      }
      this.showConditionField = data;
    }
    // console.log(condition);
  }

  /**
   * 功能：显示Grid 工具面板（toggle）
   */
  action_columnConfig() {
    if (this.sideBar === '')
      this.sideBar = 'columns';
    else
      this.sideBar = '';
  }

  /**
   * 功能：后端导出 XLS
   */
  action_download() {
    if (this.rowModelType == 'clientSide') {
      this.front_download();
    } else {
      //this.end_download();
      let downloadData = [];
      this.downloadPage = 0;
      this.isDownloading = true;
      this.setButtonLoadingStatus('action_download', true);

      this.queryDownloadData(downloadData, this.columnDefsMeta);
    }
  }

  /**
   * 导出：增加下载任务，页面显示离线下载
   */
  action_export() {
    this.createTaskDownload();
  }


  /***
   * 前端导出
   */
  private front_download() {
    this.setButtonLoadingStatus('action_download', true);
    if (this.rowData && this.rowData.length === 0) {
      this.msg.info(`查询结果为空`);
      this.setButtonLoadingStatus('action_download', false);
      return;
    }
    const columnList = this.gridOptions.columnDefs;
    this.exportExcelService.exportWithDealData(columnList, this.rowData, this.title);
    this.setButtonLoadingStatus('action_download', false);
  }

  /***
   * 后端导出
   */
  private end_download() {
    this.setButtonLoadingStatus('action_download', true);

    const columnList = this.columnDefsMeta;
    const gridheaderList = [];
    for (let i = 0, len = columnList.length; i < len; i++) {
      const temp = {};

      // 由于加上了一个 field 值为 A，导致下载报错
      if (!columnList[i]['headerName']) continue;
      if (columnList[i]['field'] == 'dialogButton') continue;

      temp['field'] = columnList[i]['field'];
      temp['title'] = columnList[i]['headerName'];
      gridheaderList.push(temp);
    }

    const sendData = {};
    sendData['condition'] = this.getConditionList(this.conditionField).conditionList;
    sendData['queryid'] = this.api;
    sendData['queryname'] = this.title;
    sendData['gridheader'] = gridheaderList;
    sendData['customAction'] = this.customAction;
    sendData['customQuery'] = this.customQuery;
    this.apiService.export('pub.downXls', { 'body': JSON.stringify(sendData) }).subscribe(
      (body) => {
        try {
          if (body.type === 'application/octet-stream') {
            saveAs(body, decodeURI(`${this.title}.zip`));
          }

          if (body.type === 'application/json') {
            let b = new Blob([body], { type: 'application/json' });
            let fr = new FileReader();
            let local = this;
            fr.onload = function() {
              const resultData = JSON.parse(this.result.toString());
              if (resultData.header.code !== 'success') {
                let error = resultData.header.message;
                local.msg.error(error, { apesDuration: 5000 });
              }
            };
            fr.readAsText(b);
          }
        } finally {
          this.setButtonLoadingStatus('action_download', false);
        }
      }, () => {
        this.setButtonLoadingStatus('action_download', false);
      });
  }

  private createTaskDownload() {
    this.setButtonLoadingStatus('action_export', true);

    const columnList = this.columnDefsMeta;
    const gridHeaderList = [];
    for (let i = 0, len = columnList.length; i < len; i++) {
      const temp = {};

      // 由于加上了一个 field 值为 A，导致下载报错
      if (!columnList[i]['headerName']) continue;
      if (columnList[i]['field'] == 'dialogButton') continue;

      temp['field'] = columnList[i]['field'];
      temp['title'] = columnList[i]['headerName'];
      gridHeaderList.push(temp);
    }

    const sendData = {};
    sendData['condition'] = this.getConditionList(this.conditionField).conditionList;
    sendData['queryid'] = this.api;
    sendData['queryname'] = this.title;
    sendData['gridheader'] = gridHeaderList;
    sendData['customAction'] = this.customAction;
    sendData['customQuery'] = this.customQuery;

    this.apiService.post('task.download.create', { 'body': JSON.stringify(sendData) }).subscribe(
      body => {
        // 发送创建下载任务的消息
        body['nowDate'] = dateFormat('yyyy-MM-dd HH:mm:ss', new Date());
        this.events.publish('task.download.create', body);
        this.setButtonLoadingStatus('action_export', false);
      }, () => {
        this.setButtonLoadingStatus('action_export', false);
      });

  }


  /**
   * 生成excl
   * @param data
   * @param col
   * @private
   */
  private generateExcl(downloadData, col) {
    let exportName = this.title && this.title != '' ? this.title : '导出文件';
    exportName += format(new Date(), 'YYYYMMDDHHmm');
    let data = [];
    let localCol = [];
    let filterCol = [];
    // data = [col.map(i => i.headerName)];
    // filterCol = col.filter(i => !i.hasOwnProperty('exportHide'));
    filterCol = col.filter((i) => {
      if (i.hasOwnProperty('exportHide')) {
        let expression = i.exportHide;
        return !this.expressionService.evaluate(expression, {
          context: this.ctx,
        });
      } else {
        return true;
      }
      // !i.hasOwnProperty('exportHide');
    });
    data = [filterCol.map((i) => {
      let name;
      if (i.hasOwnProperty('headerGroup')) {
        name = i.headerGroup + '-' + i.headerName;
      } else {
        name = i.headerName;
      }
      return name;
    })];
    downloadData.forEach((i, index) => {
        if (index == 0) {
          let bExpansion = false;
          filterCol.map((c) => {
              let value = deepClone(i[c.field as string]);
              if (value instanceof Object) {
                localCol = [...localCol, ...this.objectToExpansion(value, c)];
                bExpansion = true;
              } else {
                c.fieldMeta = c.field;
                localCol.push(c);
              }
            },
          );
          if (bExpansion) data = [localCol.map(i => i.headerName)];
        }
        data.push(
          localCol.map(c => {
              let value = deepClone(i[c.fieldMeta as string]);
              let key = replaceAll(c.field, c.fieldMeta, '');
              if (value instanceof Object) {
                if (c['exportFormatter']) {
                  let expression = c['exportFormatter'];
                  value = this.expressionService.evaluate(expression, {
                    value: value,
                    data: i,
                  });
                } else {
                  value = value[key];
                }
                if (value == undefined) {
                  value = i[c.field as string].description;
                }
              } else {
                if (c['exportFormatter']) {
                  let expression = c['exportFormatter'];
                  value = this.expressionService.evaluate(expression, {
                    value: value,
                    data: i,
                  });
                }
              }
              // 处理序号字段为空的问题
              if (c.field === 'operation') value = data.length;

              return value;
            },
          ));
      },
    );
    this.xlsx.export({
      filename: exportName += '.xlsx',
      sheets: [
        {
          data: data,
          name: '数据',
        },
      ],
    });
  }

  /**
   *  下载有对象展开数据
   */
  private objectToExpansion(value, c) {
    let columns = [];
    for (const key in value) {
      let localKey = key.toUpperCase();
      if (localKey == 'ID') {
        columns.push({ field: c.field + key, headerName: c.headerName + '编码', fieldMeta: c.field });
      } else if (localKey == 'NAME') {
        columns.push({ field: c.field + key, headerName: c.headerName + '名称', fieldMeta: c.field });
      }
    }
    return columns;
  }

  /**
   * 功能：查询后台数据(下载)
   */
  private queryDownloadData(data, col) {

    let totalQuantity = 300000; // 下载控制数
    if (!this.conditionField && this.conditionField.length === 0) return;

    // 检查输入条件
    const conditionParam = this.getConditionList(this.conditionField);
    if (!conditionParam.flag) return;  // 必填项未输入
    if (conditionParam.conditionList.length === 0) {  // 检查什么都不输入的情况下，不让查询
      // return;
    }
    const sendData = {};
    sendData['noSum'] = this.noSum;
    sendData['condition'] = conditionParam.conditionList;
    sendData['size'] = 2000;
    sendData['page'] = this.downloadPage;
    sendData['queryid'] = this.api;
    sendData['customAction'] = this.customAction;
    sendData['customQuery'] = this.customQuery;

    let fieldKey = '_orderField';
    const orderFieldValue = this.model[fieldKey];
    if (orderFieldValue && orderFieldValue.length > 0) {
      sendData['_orderField'] = orderFieldValue[0];
      if (orderFieldValue.length > 1) {
        orderFieldValue.forEach(value => {
          if (sendData['_orderField'] != value) {
            sendData['_orderField'] += ';' + value;
          }
        });
      }
      fieldKey = '_orderType';
      const orderTypeValue = this.model[fieldKey];
      if (orderTypeValue) {
        sendData['_orderType'] = orderTypeValue;
      } else {
        sendData['_orderType'] = 'desc';
      }
    }
    this.apiService.post('pub.query', { 'body': JSON.stringify(sendData) }).subscribe(
      (body) => {
        if (body) {

          if (body.total == 0) {
            this.msg.info(`查询结果为空`);
            this.isDownloading = false;
            this.setButtonLoadingStatus('action_download', false);
            return;
          }

          //if (body.size) this.pagination.pageSize = body.size;
          body.content.forEach((i) => {
            data.push(i);
          });
          this.pagination.total = body.total;
          this.pagination.pages = body.pages;

          if (body.total > totalQuantity) {
            this.msg.info(`数据量过大！目前仅支持30W行以下数据下载`);
            this.isDownloading = false;
            this.percent = 100;
            this.setButtonLoadingStatus('action_download', false);
            return;
          }

          //需求要求放开控制 初50页 10w,原100页 20w,
          // if (this.pagination.total <= data.length || this.downloadPage >= 250)
          if (this.pagination.total <= data.length) {
            // if (this.downloadPage >= 250) {
            //   this.msg.info(`数据量过大！目前仅支持20W行数据下载`);
            // }
            this.generateExcl(data, col);
            this.isDownloading = false;
            this.percent = 100;
            this.setButtonLoadingStatus('action_download', false);
          } else {
            this.downloadPage = this.downloadPage + 1;
            this.percent = Math.round(this.downloadPage / this.pagination.pages * 100);
            this.queryDownloadData(data, col);
          }
        } else {
          this.msg.info(`下载接口报错！`);
        }

      }, () => {
        this.autoSizeAll();
      });
  }


  /**
   * 功能：查询后台数据
   */
  private queryData(page?) {
    if (!this.conditionField && this.conditionField.length === 0) return;

    // 检查输入条件
    const conditionParam = this.getConditionList(this.conditionField);
    if (!conditionParam.flag) return;  // 必填项未输入
    if (conditionParam.conditionList.length === 0 && this.queryConditions) {  // 检查什么都不输入的情况下，不让查询
      this.msg.error('查询条件不能都为空!');
      return;
    }

    this.setButtonLoadingStatus('action_query', true);
    const sendData = {};
    sendData['noSum'] = this.noSum;
    sendData['condition'] = conditionParam.conditionList;
    sendData['size'] = this.pagination.pageSize;
    sendData['page'] = this.pagination.currentPage;
    if (page) {
      sendData['page'] = this.pagination.currentPage - 1;
    }
    sendData['queryid'] = this.api;
    sendData['customAction'] = this.customAction;
    sendData['customQuery'] = this.customQuery;

    let fieldKey = '_orderField';
    const orderFieldValue = this.model[fieldKey];
    if (orderFieldValue && orderFieldValue.length > 0) {
      sendData['_orderField'] = orderFieldValue[0];
      if (orderFieldValue.length > 1) {
        orderFieldValue.forEach(value => {
          if (sendData['_orderField'] != value) {
            sendData['_orderField'] += ';' + value;
          }
        });
      }
      fieldKey = '_orderType';
      const orderTypeValue = this.model[fieldKey];
      if (orderTypeValue) {
        sendData['_orderType'] = orderTypeValue;
      } else {
        sendData['_orderType'] = 'desc';
      }
    }


    if (this.rowModelType == 'clientSide') {
      this.gridApi.showLoadingOverlay();
      this.apiService.post('pub.query', { 'body': JSON.stringify(sendData) }).subscribe(
        (body) => {
          if (body) {
            this.pagination.total = body.total;
            if (body.size) this.pagination.pageSize = body.size;
            const tempRowData: any[] = body.content;
            this.gridOptions.api.setRowData(tempRowData);
            this.rowData = tempRowData;

            if (this.rowData.length === 0) {
              this.msg.info(`未找到满足条件的数据`);
              this.pinnedBottomRowData = [];
            }

            if (body.tableHeader && body.tableHeader.length > 0) {
              this.resetColumnDefs(body.tableHeader);
            }

            // 合计字段
            const sumFieldObj = this.getSumField();
            if (sumFieldObj.sumFieldList.length > 0 && body.footer) {
              this.setPinnedBottomRowData(sumFieldObj.fieldObj, sumFieldObj.sumFieldList, body.footer, this.rowData.length);
            }

            // 标签列表
            if (body.hasOwnProperty('labelList')) {
              this.subject.publish(this.ctx, 'labelListData', body.labelList);
              this.setContentHeight();
            }
          }
          this.setButtonLoadingStatus('action_query', false);
          this.autoSizeAll();
          this.gridApi.hideOverlay();
        }, () => {
          this.setButtonLoadingStatus('action_query', false);
          this.autoSizeAll();
          // this.setContentHeight();
        });
    } else {
      let dataSource = {
        rowCount: null,
        getRows: (params: any) => this.getRows(params, [], sendData),
      };
      //this.gridApi.setDatasource(dataSource);
      this.gridApi.setServerSideDatasource(dataSource);
    }

  }

  private queryListData() {
    if (!this.conditionField && this.conditionField.length === 0) return;

    // 检查输入条件
    const conditionParam = this.getConditionList(this.conditionField);
    if (!conditionParam.flag) return;  // 必填项未输入
    if (conditionParam.conditionList.length === 0 && this.queryConditions) {  // 检查什么都不输入的情况下，不让查询
      this.msg.error('查询条件不能都为空!');
      return;
    }

    this.setButtonLoadingStatus('action_query', true);
    const sendData = {};
    sendData['condition'] = conditionParam.conditionList;
    sendData['queryid'] = this.api;
    sendData['customAction'] = this.customAction;
    sendData['customQuery'] = this.customQuery;

    this.apiService.post('pub.query', { 'body': JSON.stringify(sendData) })
      .subscribe((body) => {
          if (body) {
            console.log('查询结果', body);
            this.listData = body;
            if (this.listData.length === 0) this.msg.info(`未找到满足条件的数据`);
          }
          this.setButtonLoadingStatus('action_query', false);
        },
      );
  }

  private queryIframeData() {
    if (!this.conditionField && this.conditionField.length === 0) return;

    // 检查输入条件
    const conditionParam = this.getIframeConditionList(this.conditionField);
    if (!conditionParam.flag) return;  // 必填项未输入
    if (conditionParam.conditionList.length === 0 && this.queryConditions) {  // 检查什么都不输入的情况下，不让查询
      this.msg.error('查询条件不能都为空!');
      return;
    }
    this.iframeLoading = true;
    this.iframeShowUrl = '';

    this.setButtonLoadingStatus('action_query', true);
    this.apiService.post('uReport.getUrl', {}).subscribe((body) => {
      if (exists(body)) {
        console.log(body);
        let http = body;
        let type = this.iframeShowType;
        let url = http + type + '?_u=oracle:' + this.iframeUrl;
        let conditionList = conditionParam.conditionList;
        conditionList.forEach((list) => {
          let con = '&' + list.field + '=' + list.value;
          url += con;
        });
        console.log(url);
        this.iframeLoading = false;
        this.iframeShowUrl = url;
      }
      this.setButtonLoadingStatus('action_query', false);
    });
  }

  private getRows(params: any, data: any, sendData: any) {
    sendData['size'] = this.pagination.pageSize;
    sendData['page'] = this.pagination.currentPage;
    this.gridApi.showLoadingOverlay();
    // TODO 检查返回值是否不为空数组
    this.apiService.post('pub.query', { 'body': JSON.stringify(sendData) })
      .subscribe((items) => {
        if (items) {
          if (items.tableHeader && items.tableHeader.length > 0 && this.pagination.currentPage == 0) {
            this.resetColumnDefs(items.tableHeader);
          }
          this.pagination.total = items.total;
          const itemsLength = items.content.length;
          if (itemsLength > 0 && itemsLength >= this.pagination.pageSize) {
            this.pagination.currentPage = this.pagination.currentPage + 1;
          }
          if (itemsLength == 0 || itemsLength < this.pagination.pageSize) {
            this.pagination.lastRow = this.pagination.currentPage * this.pagination.pageSize + itemsLength;
          }
          this.loadingTotal = this.pagination.lastRow !== -1 ? this.pagination.lastRow : params.request.endRow;
          params.successCallback(items.content, this.pagination.lastRow);
          if (itemsLength === 0 && this.pagination.lastRow <= 0) {
            this.msg.info(`未找到满足条件的数据`);
            this.pinnedBottomRowData = [];
          }
          // 合计字段
          const sumFieldObj = this.getSumField();
          if (sumFieldObj.sumFieldList.length > 0 && items.footer) {
            this.setPinnedBottomRowData(sumFieldObj.fieldObj, sumFieldObj.sumFieldList, items.footer, itemsLength);
          }
          // 标签列表
          if (items.hasOwnProperty('labelList')) {
            this.subject.publish(this.ctx, 'labelListData', items.labelList);
            this.setContentHeight();
          }
        } else {
          params.successCallback([], 0);
          // 标签列表
          if (items.hasOwnProperty('labelList')) {
            this.subject.publish(this.ctx, 'labelListData', []);
            this.setContentHeight();
          }
        }
        this.gridApi.hideOverlay();
        this.setButtonLoadingStatus('action_query', false);
        // this.setContentHeight();
      }, () => {
        this.setButtonLoadingStatus('action_query', false);
        // this.setContentHeight();
      });
  }

  /**
   * 功能：计算出合计的字段
   * @param fieldObj
   * @param sumFieldList
   * @param sumResultList
   */
  setPinnedBottomRowData(fieldObj, sumFieldList, sumResultList, bRow) {
    if (bRow > 0) {
      for (let i = 0, len = sumFieldList.length; i < len; i++) {
        const fieldKey = sumFieldList[i];
        fieldObj[fieldKey] = sumResultList[0][fieldKey];
      }
    } else {
      fieldObj = [];
    }
    fieldObj['hideBtnBar'] = 'true';

    this.pinnedBottomRowData = [fieldObj];
  }

  /**
   * 功能：拼接查询条件
   * @returns {any[]}
   */
  getConditionList(conditionField: any): { flag: boolean, conditionList: any[] } {
    // flag 用于判断必输项是否输入完成
    let returnParam = { flag: true, conditionList: [] };
    let conditionList = [];
    for (const tempConditionField of conditionField) {
      let fieldKey = tempConditionField.key;
      if (fieldKey === '_orderField' || fieldKey === '_orderType' || fieldKey === '_showType') continue;
      let fieldValue = this.model[fieldKey];

      if (fieldValue === undefined && tempConditionField.hasOwnProperty('defaultValue')) {
        fieldValue = tempConditionField.defaultValue;
      }

      const config = tempConditionField.templateOptions.config;
      const required = tempConditionField.templateOptions.required;

      // 判断查询的操作条件（=、like...）
      let operatorValue = '';
      if (config.value) {
        operatorValue = config.value;
      } else if (config.operators.length > 0) {
        operatorValue = config.operators[0];
      }

      // 判断是否必填
      if (required && (fieldValue === undefined || fieldValue === null || fieldValue.length == 0)) {
        this.msg.error(`${tempConditionField.templateOptions.label}为必填项`, { apesDuration: 5000 });
        conditionList = [];
        returnParam.flag = false;
        break;
      }
      // (!fieldValue && (config.type !== 'boolean')) ||
      if (fieldValue === undefined || fieldValue === null || fieldValue.length === 0) {
        continue;
      }
      // 处理存在明细表字段的情况
      fieldKey = replaceAll(fieldKey, '#', '.');

      if (config.type === 'dateRange') {
        let starValue;
        let endValue;
        if (typeof fieldValue[0] == 'string' || typeof fieldValue[0] == 'number') {
          starValue = new Date(fieldValue[0]);
          endValue = new Date(fieldValue[1]);
          this.model[fieldKey][0] = starValue;
          this.model[fieldKey][1] = endValue;
        } else {
          starValue = fieldValue[0];
          endValue = fieldValue[1];
        }

        let formatType = config.hasOwnProperty('valueFormatter') ? config['valueFormatter'] : 'yyyy-MM-dd';
        const dataModelStar = {
          field: fieldKey,
          operator: 'GTE',
          value: this.dateRangeFormat(formatType, starValue, 'GTE'),
          type: 'date',
        };
        const dataModelEnd = {
          field: fieldKey,
          operator: 'LTE',
          value: this.dateRangeFormat(formatType, endValue, 'LTE'),
          type: 'date',
        };

        conditionList.push(dataModelStar);
        conditionList.push(dataModelEnd);
      } else if (config.type === 'monthRange') {
        const dataModelStar = {
          field: fieldKey,
          operator: 'GTE',
          value: dateFormat('yyyy-MM-dd', fieldValue[0]) + ' 00:00:00',
          type: 'date',
        };
        const dataModelEnd = {
          field: fieldKey,
          operator: 'LTE',
          value: dateFormat('yyyy-MM-dd', fieldValue[1]) + ' 23:59:59',
          type: 'date',
        };

        conditionList.push(dataModelStar);
        conditionList.push(dataModelEnd);
      } else if (config.type === 'date') {
        const dataModel = { type: 'date' };

        dataModel['field'] = fieldKey;
        dataModel['operator'] = operatorValue ? operatorValue : 'EQ';
        dataModel['value'] = dateFormat('yyyy-MM-dd', fieldValue);
        conditionList.push(dataModel);
      } else {
        const dataModel = {};

        dataModel['field'] = fieldKey;
        dataModel['operator'] = operatorValue ? operatorValue : 'EQ';
        dataModel['value'] = type(fieldValue) == 'string' ?
          fieldValue.trim() : fieldValue;
        conditionList.push(dataModel);
      }
    }
    returnParam.conditionList = conditionList;
    return returnParam;
  }

  getIframeConditionList(conditionField: any) {
    let returnParam = { flag: true, conditionList: [] };
    let conditionList = [];
    for (const tempConditionField of conditionField) {
      let fieldKey = tempConditionField.key;
      if (fieldKey === '_orderField' || fieldKey === '_orderType' || fieldKey === '_showType') continue;
      let fieldValue = this.model[fieldKey];

      const config = tempConditionField.templateOptions.config;
      const required = tempConditionField.templateOptions.required;

      // 判断是否必填
      if (required && !fieldValue) {
        this.msg.error(`${tempConditionField.templateOptions.label}为必填项`, { apesDuration: 5000 });
        conditionList = [];
        break;
      }

      if (fieldValue === undefined || fieldValue === null || fieldValue.length === 0) {
        continue;
      }

      let dataModel = {};

      if (config.type === 'date') {
        dataModel['field'] = fieldKey;
        dataModel['value'] = dateFormat('yyyy-MM-dd', fieldValue);
        conditionList.push(dataModel);
      } else if (type(fieldValue) == 'array') {
        dataModel['field'] = fieldKey;
        dataModel['value'] = fieldValue.join();
        conditionList.push(dataModel);
      } else {
        dataModel['field'] = fieldKey;
        dataModel['value'] = fieldValue;
        conditionList.push(dataModel);
      }
    }
    returnParam.conditionList = conditionList;
    return returnParam;
  }

  dateRangeFormat(type, value, operator) {
    let date;
    if (type != 'yyyy-MM-dd') {
      date = dateFormat(type, value);
    } else {
      let ope = operator == 'GTE' ? ' 00:00:00' : ' 23:59:59';
      date = dateFormat(type, value) + ope;
    }
    return date;
  }

  /**
   * 功能：获取需要合计的字段
   * sumFieldList 合计字段数组，用来存放需要合计的字段
   * fieldObj 一行数据的对象，用于合计展示
   * sumFieldData 发送给后端合计数据的精度
   * sumFieldStr 合计字段
   * @returns {{sumFieldList: any[]; fieldObj: {}; sumOption: {}; sumFieldStr: string}}
   */
  getSumField() {
    const sumFieldList = [], fieldObj = {};
    let sumOption = {}, sumFieldStr = '';
    // const columnList = this.gridOptions.columnDefs;
    const columnList = this.columnDefsMeta;
    for (let i = 0, lent = columnList.length; i < lent; i++) {
      const columnObj = columnList[i];
      fieldObj[columnObj['field']] = '';

      if (columnObj['sum'] && toBoolean(columnObj['sum'])) {
        sumFieldList.push(columnObj['field']);
        sumFieldStr += `${columnObj['field']};`;
        sumOption[columnObj['field']] = { scale: columnObj['scale'] ? columnObj['scale'] : 2 };
      }
    }
    return { sumFieldList: sumFieldList, fieldObj: fieldObj, sumOption: sumOption, sumFieldStr: sumFieldStr };
  }

  /**
   * 功能：增加按钮加载中动画
   * @param {string} operationId 按钮Id
   * @param {boolean} status 设置状态
   */
  setButtonLoadingStatus(operationId: string, status: boolean) {
    const tempButtonBar = this.buttonBar.map((button) => {
      if (button.operationId === operationId) {
        button['loading'] = status;
        button['disabled'] = status;
      }
      return button;
    });

    this.buttonBar = [];
    this.buttonBar = tempButtonBar;
    this.ctx['customBtn'] = this.buttonBar;
  }

  onSelectionChanged() {
    const selectedRow = this.gridOptions.api.getSelectedRows();
    this.resultData = selectedRow;
  }

  setCurrIndex(param) {
    this.gridApi.forEachNode(function(rowNode) {
      if (rowNode.rowIndex == param.node.rowIndex) {
        rowNode.setDataValue('A', true);
      } else {
        rowNode.setDataValue('A', false);
      }
    });
  }

  /**
   * 功能：点击分页码时事件
   */
  onPageIndexChange() {
    this.queryData(true);
  }

  onGridReady(params) {
    this.gridApi = params.api;
    this.gridColumnApi = params.columnApi;
    if (this.rowModelType == 'clientSide') {
      this.gridApi.hideOverlay();
    }
    this.autoSizeAll();
  }

  sizeToFit() {
    this.gridApi.sizeColumnsToFit();
  }

  autoSizeAll() {
    let allColumnIds = [];
    this.gridColumnApi.getAllColumns().forEach(column => {
      if (!column.colDef.hasOwnProperty('width')) {
        allColumnIds.push(column.colId);
      }

    });
    this.gridColumnApi.autoSizeColumns(allColumnIds);
  }

  showBtnType(btn) {
    let type = 'primary';
    if (btn.hasOwnProperty('type')) {
      type = this.expressionService.evaluate(btn.type, {
        context: this.ctx,
        form: this.ctx['form'],
        model: this.rowData,
      });
    }
    return type;
  }

  orderTyepPush() {

    let config = {
      downFormatter: 'value.name',
      inable: false,
      items: '[{\'id\':\'asc\', \'name\': \'升序\'},{\'id\':\'desc\', \'name\': \'降序\'}]',
      nullable: false,
      operators: ['EQ'],
      required: false,
      type: 'select',
      value: '',
      valueFormatter: 'value.name',
    };
    let templateOptions = {
      label: '升/降序',
      config: config,
      placeholder: '请输入升/降序名称',
    };
    let field = {
      key: '_orderType',
      // defaultValue: "desc",
      templateOptions: templateOptions,
      type: 'conditionInput',
    };

    return field;
  }

  orderFilePush() {
    let items = [];
    if (this.columnDefs) {
      this.columnDefs.forEach(e => {
        let item = {
          id: e.field,
          name: e.headerName,
        };
        items.push(item);
      });
    }

    let orderConfig = {
      downFormatter: 'value.name',
      inable: false,
      items: JSON.stringify(items),

      multiple: true,
      nullable: false,
      operators: ['EQ'],
      required: false,
      type: 'select',
      value: '',
      valueFormatter: 'value.name',
    };
    let orderTemplateOptions = {
      label: '排序字段',
      config: orderConfig,
      placeholder: '请输入排序字段名称',
    };
    let orderField = {
      key: '_orderField',
      templateOptions: orderTemplateOptions,
      type: 'conditionInput',
    };
    return orderField;
  }


  resetModel() {
    this.model['_orderField'] = [];
    this.model['_orderField_name'] = [];
    let items = [];
    this.conditionField.forEach((field) => {
      if (field.key == '_orderField') {
        if (this.columnDefs) {
          this.columnDefs.forEach(e => {
            let item = {
              id: e.field,
              name: e.headerName,
            };
            items.push(item);
          });
        }
        if (field.templateOptions.hasOwnProperty('componentRef')) {
          field.templateOptions.componentRef.items = items;
        } else {
          field.templateOptions.config.items = JSON.stringify(items);
        }
      }
    });
  }

  // 重置表格数据
  resetGridData() {
    if (this.rowModelType == 'clientSide') {
      this.rowData = [];
    } else {
      this.pinnedBottomRowData = [];
      this.loadingTotal = 0;
      this.pagination = {
        total: 0,
        currentPage: 0,
        lastRow: -1,
        pageSize: 50,
        pages: 0,
      };
      let dataSource = {
        rowCount: null,
        getRows: (params: any) => {
          params.successCallback([], 0);
        },
      };
      this.gridApi.setServerSideDatasource(dataSource);
    }
  }


  /***
   * 重置表头
   */
  public resetColumnDefs(columnDefs) {
    let bGroup = false;
    this.columnDefs = deepClone(columnDefs);

    let detailColumnDefs = [];
    if (this.isDetail) {
      this.detailCellRendererParams = {
        detailRowHeight: this.detailRowHeight,
        detailList: this.detailList,
        detailGridOptions: {
          options: this.detailRowOptions,
          columnDefs: [],
        },
        getDetailRowData: function(params) {
          params.successCallback(params.data);
        },
      };
    }

    // 转换grid-operating-button参数
    this.columnDefs.forEach(element => {
      // let colDef = extend(true, {}, element);
      if (element.buttonList) {
        let buttonList;
        buttonList = replaceAll(element.buttonList, '\'', '"');
        buttonList = replaceAll(buttonList, '`', '\'');
        buttonList = JSON.parse(buttonList);
        buttonList.forEach(btn => {
          let cellButtonListDisabled = btn.disabled || 'false';
          btn.disabled = this.expressionService.eval(cellButtonListDisabled, {
            // context: this.formState,
            form: this.form,
            // model: this.formState.model,
          });
        });
        element.buttonList = buttonList;
      }
      element.enableRowGroup = true;
      element.enablePivot = true;
      if (element.hasOwnProperty('valueFormatter')) {
        if (element.valueFormatter == 'currency') {
          element.valueFormatter = agCurrency;
          element['valueFormatterMeta'] = 'currency';
        } else if (element.valueFormatter == 'number') {
          element.valueFormatter = agNumber;
          element['valueFormatterMeta'] = 'number';
        }
      }
      if (element.hasOwnProperty('hideExpression')) {
        element.hide = this.expressionService.eval(element.hideExpression, {
          context: this.ctx,
          form: this.form,
        });
      }
      if (element.hasOwnProperty('changeCellStyle')) {
        let that = this;
        element.cellStyle = (params) => {
          let CellStyle = element['changeCellStyle'];
          let res = that.expressionService.eval(CellStyle, params);
          return res;
        };
      }
      if (element.hasOwnProperty('headerGroup')) {
        element.suppressMovable = true;
        bGroup = true;
      }

      if (element.hasOwnProperty('checkboxSelection')) {
        element.checkboxSelection = true;
      }

      if (element.hasOwnProperty('headerCheckboxSelection')) {
        element.headerCheckboxSelection = true;
      }

      if (element.hasOwnProperty('headerCheckboxSelectionFilteredOnly')) {
        // 是否全选非筛选状态的行（默认不全选）
        element.headerCheckboxSelectionFilteredOnly = true;
      }

      if (this.isDetail && element.hasOwnProperty('customDetail')) {
        detailColumnDefs.push(deepClone(element));
        element.hide = true;
      }

    });
    this.columnDefs.push({ field: 'A', hide: true });
    this.columnDefsMeta = deepClone(this.columnDefs);
    if (this.isDetail) {
      this.detailCellRendererParams.detailGridOptions.columnDefs = detailColumnDefs;
    }
    if (bGroup) {
      this.setHeaderGroup();
    }
  }

  private setHeaderGroup() {
    let groupColumnDefs = [];
    this.columnDefs.forEach((item) => {
      let columnDef = item;
      if (item.hasOwnProperty('headerGroup')) {
        if (item.headerGroup == 'false') {
          return;
        }
        columnDef = {};
        columnDef['headerName'] = item.headerGroup;
        let filterColumnDefs = this.columnDefs.filter((v) => v.headerGroup == item.headerGroup);
        columnDef['children'] = filterColumnDefs;
        //this.columnDefs.filter((v) => v.headerGroup ==item.headerGroup).forEach(item => item.headerGroup ='false');
        filterColumnDefs.forEach(item => item.headerGroup = 'false');
      }
      columnDef.suppressMovable = true;
      groupColumnDefs.push(columnDef);
    });
    this.columnDefs = groupColumnDefs;
  }

  clickBtn(btn) {
    let callbackBody = btn.callback;

    this.expressionService.evaluate(callbackBody, {
      context: this.ctx,
      form: this.ctx['form'],
      model: this.rowData,
    }, true);
  }

  action_print() {
    let data = this.gridApi.getSelectedRows();
    this.batchPrintService.batchPrint(this.printTemplate, data);
  }
}
